import React, { useEffect, useState, useCallback } from 'react';
import { Message, Upload } from '@arco-design/web-react';
import aliOss from '@/utils/aliOss';
import { guid } from '@/utils/common';
import { UploadItem } from '@arco-design/web-react/es/Upload';

function MultipleImgUpload(props: {
  onChange: (urls: Array<string>) => void;
  urls?: Array<string>;
  disabled?: boolean;
}) {
  const { onChange, urls, disabled = false } = props;
  const [files, setFiles] = useState<
    { file: File; status: 'pending' | 'success' | 'error' }[]
  >([]);
  const [allFilesUploaded, setAllFilesUploaded] = useState(false);
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    setFileList(
      urls.map((item) => {
        return {
          uid: guid(),
          url: item,
          name: item,
        };
      })
    );
  }, [urls]);

  const handleImgChange = useCallback(() => {
    // 回调
    const emitUrl = fileList.map((item) => item.url);
    onChange(emitUrl);
  }, [fileList]);

  // 统一结果显示
  useEffect(() => {
    if (allFilesUploaded) {
      const successCount = files.filter((f) => f.status === 'success').length;
      const errorCount = files.filter((f) => f.status === 'error').length;

      if (successCount > 0) {
        Message.success(`成功上传 ${successCount} 张图片`);
      }

      if (errorCount > 0) {
        Message.error(`上传失败 ${errorCount} 张图片`);
      }

      handleImgChange();

      // 重置状态
      setAllFilesUploaded(false);
      setFiles([]);
    }
  }, [allFilesUploaded, files]);

  const handleUpload = (options: any) => {
    const { file, onSuccess, onError } = options;

    // 添加文件到状态列表
    setFiles((prevFiles) => [...prevFiles, { file, status: 'pending' }]);

    aliOss
      .uploadImage(file, 'auth')
      .then((res) => {
        setFiles((prevFiles) =>
          prevFiles.map((f) =>
            f.file === file ? { ...f, status: 'success' } : f
          )
        );
        setFileList((prevFileList) => [
          ...prevFileList,
          {
            uid: guid(),
            url: res,
            name: res,
          },
        ]);
      })
      .catch((err) => {
        setFiles((prevFiles) =>
          prevFiles.map((f) =>
            f.file === file ? { ...f, status: 'error' } : f
          )
        );
      })
      .finally(() => {
        //  在setFiles中使用回调函数，确保状态更新后再进行检查所有文件是否都已上传完成
        setFiles((prevFiles) => {
          const newFiles = prevFiles.map((f) =>
            f.file === file
              ? { ...f, status: f.status === 'pending' ? 'error' : f.status }
              : f
          );

          if (newFiles.every((f) => f.status !== 'pending')) {
            setAllFilesUploaded(true);
          }

          return newFiles;
        });
      });
  };

  const handleRemove = (file: UploadItem) => {
    const newUrl = fileList.filter((item) => item.url !== file.url);
    const emitUrl = newUrl.map((item) => item.url);
    onChange(emitUrl);
    // 过滤掉删除的图片
    setFileList((prevFileList) =>
      prevFileList.filter((f) => f.url !== file.url)
    );
  };

  return (
    <div>
      <Upload
        multiple
        imagePreview
        listType="picture-card"
        customRequest={handleUpload}
        onRemove={handleRemove}
        fileList={fileList}
        accept="image/jpeg ,image/png"
        disabled={disabled}
      />
    </div>
  );
}

export default MultipleImgUpload;
